package filters

import (
	"gitchina/kly_service/models"
	"gitchina/kly_service/util"
	_ "github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"net/http"
	"strings"
)

var IPFilterFunc = func(ctx *context.Context) {
	var g models.General
	xClientIp := ctx.Request.Header.Get("X-Client-Ip")
	clientIp := getClientIp(ctx) //ctx.Request.Header.Get("X-Real-Ip")
	if clientIp == "" {
		clientIp = "127.0.0.1"
	} else {
		serverIp := g.GetParams("server_ip")
		if clientIp == serverIp && xClientIp != "" {
			clientIp = xClientIp
		}
	}
	ctx.Request.Header.Set("X-Real-Ip", clientIp)
	if g.IsIpBlocked(clientIp) {
		util.GetLogger().Error("[ip-block] - error:client-ip:%s is blocked!", clientIp)
		http.Error(ctx.ResponseWriter, "", 403)
	}
}

func getClientIp(ctx *context.Context) (ip string) {
	xff := strings.Split(ctx.Request.Header.Get("X-Forwarded-For"), ",")
	if len(xff) > 0 {
		ip = xff[0]
	}
	return
}
